package com.example.academic_affairs_system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.academic_affairs_system.exception.SystemException;
import com.example.academic_affairs_system.mapper.AasRoleMapper;
import com.example.academic_affairs_system.model.entity.AasRole;
import com.example.academic_affairs_system.service.IAasRoleService;
import com.example.academic_affairs_system.service.IAasUserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 服务实现类
 *
 * @author hjx
 * @since 2023-01-31
 */
@Service
public class AasRoleServiceImpl extends ServiceImpl<AasRoleMapper, AasRole>
    implements IAasRoleService {
  @Resource IAasUserRoleService iAasUserRoleService;

  @Override
  public AasRole getRoleByUserId(long userId) {
    return baseMapper.selectById(iAasUserRoleService.getRoleIdByUserId(userId));
  }

  @Override
  public long getStudentRoleId() {
    long student = getRoleByRoleName("学生");
    if (student == -1) {
      throw new SystemException(-999, "没有指定学生角色", "请联系系统负责人");
    }
    return student;
  }

  @Override
  public long getTeacherRoleId() {
    // FIXME: 目前老师、教师和班主任的性质完全相同，不需要进行过多的指定
    List<AasRole> teachers =
        baseMapper.selectList(
            Wrappers.<AasRole>lambdaQuery().in(AasRole::getRoleName, "老师", "教师", "班主任"));
    if (CollectionUtil.isEmpty(teachers)) {
      throw new SystemException(-999, "没有指定有关教师的角色", "请联系系统负责人");
    }
    Optional<AasRole> first = teachers.stream().findFirst();
    if (first.isPresent()) {
      return first.get().getId();
    }
    return -1;
  }

  @Override
  public long getRoleByRoleName(String roleName) {
    AasRole role =
        baseMapper.selectOne(Wrappers.<AasRole>lambdaQuery().eq(AasRole::getRoleName, roleName));
    if (role == null) {
      return -1;
    }
    return role.getId();
  }
}
